<?php
require_once("lib/util.php");
require_once("lib/db.php");
require_once("lib/incident.php");
require_once("lib/user.php");
session_start();
$category = $_GET["category"];
$creator_id = @$_SESSION["logged_in_user"];
connect();
$incidents= get_all_incidents($category);
$categories= get_categories();

if ($creator_id){
$user_name = query_name($creator_id);
$ids = get_all_ratings_by($creator_id);
$incidents_created = get_incidents_created($creator_id);
$incidents = set_is_created ($incidents, $incidents_created);
$incidents = set_is_rated ($incidents, $ids);
}
$incidents = set_total_rating ($incidents);
render("view_all", array( "incidents" => $incidents, "category" => $category, "categories" => $categories));
close();

function get_incident_creator($incidents){
	$creators = array();
	foreach ($incidents as $incident) {
	$creators[] = $incident["incident_creator"];
	print_r($creators);
	}
}
	

function get_all_incidents($category) {
	$incident_query= "SELECT * FROM incidents WHERE category_id = ? ORDER BY created DESC"; 
	$incident = query ($incident_query, array($category));
	return $incident ;
}
function get_all_ratings_by($user_id){
	$query = "SELECT incident_id from ratings WHERE rater_user_id = ?";
	$incidents = query ($query, array($user_id));
	return get_incident_ids_from_result($incidents);
}

function get_incidents_created($creator_id){
	$creator_query = "SELECT incident_id from incidents WHERE creator_user_id = ?";
	$incidents_created = query($creator_query, array($creator_id));
	return get_incident_ids_from_result($incidents_created);
}

function get_incident_ids_from_result ($incidents) {
	$ids = array(); 
	foreach ($incidents as $incident) {
	$ids[] = $incident["incident_id"];
	}
	return $ids;
	
}

function set_is_rated ($incidents, $rated_ids){
	$modified_incidents = array();
	foreach ($incidents as $incident) {
		$modified_incident = $incident;
		$modified_incident['is_rated'] = in_array ( $incident["incident_id"], $rated_ids);
		$modified_incidents[] = $modified_incident;
	}
	return $modified_incidents;
}


function set_is_created ($incidents, $ids){
	$modified_incidents = array();
	foreach ($incidents as $incident) {
		$modified_incident = $incident;
		$modified_incident['is_created'] = in_array ( $incident["incident_id"], $ids);
		$modified_incidents[] = $modified_incident;
	}
	return $modified_incidents;
}